$(function () {
    init_sparedetail();
    back();
    add_into_shopcart();
});

function init_sparedetail() {
    $.ajax({
        url: '/get-spare-detail',
        type: 'get',
        dataType: 'JSON',
        success: function (data) {
            if (data.status) {
                var result = data.result;
                console.log(result);
                $('#spare-name').text(result['name']);
                $('#spare-number').text(result['num']);
            } else {
                alert('数据获取失败');
            }
        }
    });
}

function back() {
    $('#back-button').click(() => {
        $.ajax({
            url: '/spare-destroy-session',
            type: 'get',
            data: 'JSON',
            success: function (data) {
                window.location.href = '/page/purchaser-spare.html';
            }
        });
    });
}

function add_into_shopcart() {
    $('#into-shopcart-button').click(() => {
        if ($('#into-store').val() != '') {
            var num = parseInt($('#spare-number').text()) + parseInt($('#into-store').val());
            if (num >= 0) {
                $.ajax({
                    url: '/output-spare',
                    type: 'POST',
                    dataType: 'JSON',
                    data: {
                        num: num,
                    },
                    success: function (data) {
                        if (data.status) {
                            console.log('complete output spare');
                            $('#into-shopcart-button').attr('class', 'btn btn-success');
                            $('#into-shopcart-button').text('出库成功');
                            $.ajax({
                                url: '/spare-destroy-session',
                                type: 'get',
                                data: 'JSON',
                                success: function (sub_data) {
                                    window.location.href = '/page/purchaser-spare.html';
                                }
                            });
                        } else {
                            alert('数据库连接失败');
                        }
                    } 
                })
            } else {
                $('#into-shopcart-button').attr('class', 'btn btn-danger');
                $('#into-shopcart-button').text('出库数量不应大于库存数');                
            }
        } else {
            $('#into-shopcart-button').attr('class', 'btn btn-danger');
            $('#into-shopcart-button').text('请输入库存数目');
        }
    });
}